package com.bridgeintelligent.tag.bulkload.api.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.IOUtils;

import java.io.*;

/**
 * @Auther: xiang
 * @Date: 2022/7/5 10:44
 * @Description: TarUtils
 * @Version 1.0.0
 */
@Slf4j
public class TarUtils {


    /**
     *
     * @Title: tarMore
     * @Description: 将一组文件打成tar包
     * @param sources 要打包的原文件数组
     * @throws
     */
    public static void tarMore(String tarFileName, File... sources) throws IOException {
        FileOutputStream out = null;
        TarArchiveOutputStream os = null;
        try {
            out = new FileOutputStream(tarFileName);
            os = new TarArchiveOutputStream(out);
            for (File file : sources) {
                os.putArchiveEntry(new TarArchiveEntry(file,getFileName(file.getName())));
                IOUtils.copy(new FileInputStream(file), os);
                os.closeArchiveEntry();
            }
        }finally {
            if(os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    log.error("关闭流异常",e);
                }
            }
        }
    }

    private static String getFileName(String name){
        return name.substring(name.lastIndexOf("_")+1);
    }
}
